package com.wang.di;

import com.wang.di.core.JustDI;
import com.wang.di.core.bean.BaseBean;
import com.wang.di.core.exception.BeanInitException;
import com.wang.di.core.exception.BeanScanException;
import com.wang.di.core.handler.AnnoHandler;
import com.wang.di.defalut.anno.DI;
import com.wang.di.defalut.anno.LogTs;
import com.wang.di.defalut.anno.NormalBeanAnno;
import com.wang.di.defalut.anno.SingleBeanAnno;
import com.wang.di.defalut.anno_executor.DIExecutor;
import com.wang.di.defalut.anno_executor.LogTsExecutor;
import com.wang.di.defalut.bean.NormalBean;
import com.wang.di.defalut.bean.SingleBean;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

// 对外暴露总指挥部
public class JustDIApplication {
    private JustDI justDI = null;

    //---------------注解解释器---------------------------------------------------------------------
    private static Map<Class<? extends Annotation>, AnnoHandler<?>> defaultExecutorMap(JustDI justDI) {
        Map<Class<? extends Annotation>, AnnoHandler<?>> map = new HashMap<>();
        map.put(DI.class, new DIExecutor(justDI));
        map.put(LogTs.class, new LogTsExecutor());
        return map;
    }

    //---------------开放接口---------------------------------------------------------------------
    public <T> T get(Class<T> clz) throws Exception {
        return this.get(clz, "");
    }

    public <T> T get(Class<T> clz, String name) throws Exception {
        return justDI.get(clz, name);
    }

    //---------------bean管理类---------------------------------------------------------------------
    private static Map<Class<? extends Annotation>, Class<? extends BaseBean>> defaultBeanMap() {
        Map<Class<? extends Annotation>, Class<? extends BaseBean>> map = new HashMap<>();
        map.put(SingleBeanAnno.class, SingleBean.class);
        map.put(NormalBeanAnno.class, NormalBean.class);
        return map;
    }

    // 开始启动
    public void start(Class<?> pkgClz,
                      Map<Class<? extends Annotation>, Class<? extends BaseBean>> customizeBeanClzMap,
                      Map<Class<? extends Annotation>, AnnoHandler<?>> customizeHandlerMap) throws BeanScanException, BeanInitException {
        // 空壳
        this.justDI = new JustDI();
        // 进行填装
        Map<Class<? extends Annotation>, Class<? extends BaseBean>> beanClzMap = defaultBeanMap();
        if(customizeBeanClzMap != null) {
            beanClzMap.putAll(customizeBeanClzMap);
        }

        Map<Class<? extends Annotation>, AnnoHandler<?>> handlerMap = defaultExecutorMap(justDI);
        if(customizeHandlerMap != null) {
            handlerMap.putAll(customizeHandlerMap);
        }

        justDI.build(handlerMap, beanClzMap);
        // 启动
        justDI.scan(pkgClz);
    }
}
